package com.tool;

import com.google.protobuf.GeneratedMessage;
import com.googlecode.protobuf.format.JsonFormat;
import com.databus.*;
import com.protobuf.MsgExpress;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class ObjectConvertor {

    public  static String ProtobufToJson(GeneratedMessage msg)
    {
        return JsonFormat.printToString(msg);
    }

    public  static <T  extends GeneratedMessage> T JsonToProtobuf(String jsonStr, Class<T> clazz) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, JsonFormat.ParseException {
        Method m = null;
        T msg = null;
        m = clazz.getMethod("newBuilder");
        GeneratedMessage.Builder builder = (GeneratedMessage.Builder) m.invoke(clazz);
        Log.debug("Json data:" + jsonStr);
        JsonFormat.merge(jsonStr, builder);
        msg = (T) builder.build();
        return msg;
    }

    public static String BeanToJson(Object bean)
    {
        JSONObject json=JSONObject.fromObject(bean);
        return json.toString();
    }

    public static <T> T JsonToBean(String jsonStr,Class<T> type)
    {
        JSONObject jsonObj=JSONObject.fromObject(jsonStr);
        return (T)JSONObject.toBean(jsonObj,type);
    }

    public static String ObjectToXML(Object bean) {
        JSONObject jsonObject = JSONObject.fromObject(bean);
        XMLSerializer xmlSerializer = new XMLSerializer();
        String xml = xmlSerializer.write(jsonObject, "UTF-8");
        return xml;
    }

    public static <T> T XmlToBean(String xmlStr,Class<T> type) {
        XMLSerializer xmlSerializer = new XMLSerializer();
        JSON json = xmlSerializer.read(xmlStr);
        return JsonToBean(json.toString(),type);
    }
}
